﻿using System;
using System.Collections.Generic;
using System.Xml;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using SolutionExtender.AppCode;
using SolutionExtender.Controls;
using SolutionExtender.Interfaces;

namespace McTools.SolutionExtender.QueuePlugin
{
    public class QueueConnector : IConnector
    {
        #region Variables

        /// <summary>
        /// IOrganization service to access CRM 2011 data
        /// </summary>
        private readonly IOrganizationService _service;

        #endregion Variables

        #region Constructor

        /// <summary>
        /// Initializes a new instance of class DuplicateRuleConnector
        /// </summary>
        /// <param name="service">IOrganization service to access CRM 2011 data</param>
        public QueueConnector(IOrganizationService service)
        {
            _service = service;
        }

        #endregion Constructor

        #region Properties

        public string ObjectName
        {
            get { return "Queue"; }
        }

        public string Description
        {
            get { return "Allows to export public queues."; }
        }

        #endregion Properties

        #region Methods

        public List<ImportResult> Import(XmlNode data)
        {
            string stringifiedData = data.OuterXml;

            var queueObject =
                (Queue) XmlSerializerHelper.Deserialize(stringifiedData, typeof (Queue));

            var queue = new Entity("queue");

            queue["allowemailcredentials"] = queueObject.AllowEmailCredentials;
            //queue["businessunitid"] = queueObject.BusinessUnitId;
            queue["description"] = queueObject.Description;
            queue["emailaddress"] = queueObject.EmailAddress;
            queue["emailpassword"] = queueObject.EmailPassword;
            queue["emailusername"] = queueObject.EmailUserName;
            queue["ignoreunsolicitedemail"] = queueObject.IgnoreUnsolicitedEmail;
            queue["name"] = queueObject.Name;
            //queue["ownerid"] = queueObject.OwnerId;
            //queue["primaryuserid"] = queueObject.PrimaryUserId;

            if (queueObject.IncomingEmailDeliveryMethod.HasValue)
                queue["incomingemaildeliverymethod"] = new OptionSetValue(queueObject.IncomingEmailDeliveryMethod.Value);
            if (queueObject.IncomingEmailFilteringMethod.HasValue)
                queue["incomingemailfilteringmethod"] =
                    new OptionSetValue(queueObject.IncomingEmailFilteringMethod.Value);
            if (queueObject.OutgoingEmailDeliveryMethod.HasValue)
                queue["outgoingemaildeliverymethod"] = new OptionSetValue(queueObject.OutgoingEmailDeliveryMethod.Value);
            queue.Id = queueObject.QueueId;

            if (queue.Id == Guid.Empty)
            {
                _service.Create(queue);
            }
            else
            {
                try
                {
                    _service.Retrieve("queue", queue.Id, new ColumnSet());
                    _service.Update(queue);
                }
                catch
                {
                    _service.Create(queue);
                }
            }

            return null;
        }

        public IExportControl GetExportControl(IOrganizationService service)
        {
            return new QueueExportControl(_service);
        }

        public string GetRecordName(XmlNode node)
        {
            return node.SelectSingleNode("Name").InnerText;
        }

        #endregion Methods
    }
}
    